<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/22
 */

namespace App\Models;

use App\Filters\InfoCategoryFilter;
use App\Traits\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * 信息分类模型
 * Class InfoCategory
 * @package App\Models
 */
class InfoCategory extends Model
{
    use BaseModel, HasFactory;

    /**
     * 指定表名
     */
    protected $table = 'info_category';

    /**
     * 能批量赋值的属性
     *
     * @var string[]
     */
//    protected $fillable = [];

    /**
     * 不能被批量赋值的属性
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * 数据显示时，设置了敏感信息字段数据中不显示
     *
     * @var array
     */
    protected $hidden = [
        'deleted_at',
        'created_at',
        'updated_at',
        'created_user_id'
    ];

    /**
     * 显示数据时类型转换
     *
     * @var array
     */
    protected $casts = [
    ];


    /**
     * 注册过滤器
     * @param $query
     * @param InfoCategoryFilter $filters
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFilter($query, InfoCategoryFilter $filters)
    {
        return $filters->apply($query);
    }

    /**
     * 关联信息模型模型
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function infoModel()
    {
        return $this->hasOne(InfoModel::class, 'id', 'info_model_id');
    }

    /**
     * 关联角色栏目权限表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function roleCategory()
    {
        return $this->hasMany(RoleCategory::class, 'info_category_id', 'id');
    }

    
    /**
     * 关联单页
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function infoPage()
    {
        return $this->hasOne(InfoPage::class, 'info_category_id', 'id');
    }

    /**
     * 关联删除
     */
    protected static function boot()
    {
        parent::boot();
        static::deleted(function ($model) {
            if ($model->type == 3) {
                // 关联删除单页
                $model->infoPage()->forceDelete();
            }
            // 关联删除角色栏目权限
            $model->roleCategory()->delete();
        });
    }
}
